package com.cafuc.javaEE.service.impl;

import com.cafuc.javaEE.common.Result;
import com.cafuc.javaEE.dao.UserDao;
import com.cafuc.javaEE.entity.User;
import com.cafuc.javaEE.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDao();
    @Override
    public Result<User> insertUser(User user) {
        //判断用户名是否重复
        User temp = userDao.getUserByUserName(user.getUserName());
        if (temp != null) {
            return new Result<>(Result.ResultStatus.FAILED.code,
                    "User name is repeat.");
        }

        //设置创建时间
        user.setCreateDate(new Date());

        // 插入 user
        userDao.insertUser(user);
        return new Result<>(Result.ResultStatus.SUCCESS.code,
                "Insert success", user);
    }

    @Override
    public Result<User> updateUser(User user) {
        //判断用户名是否重复
        User temp = userDao.getUserByUserName(user.getUserName());
        if (temp != null && temp.getId() != user.getId()) {
            return new Result<>(Result.ResultStatus.FAILED.code,
                    "User name is repeat.");
        }

        // 更改 user
        userDao.updateUser(user);
        return new Result<>(Result.ResultStatus.SUCCESS.code,
                "Update success", user);
    }

    @Override
    public User getUserById(int id) {
        return userDao.getUserById(id);
    }

    @Override
    public Result<Object> deleteUserById(int id) {
        userDao.deleteUserById(id);
        return new Result<>(
                Result.ResultStatus.SUCCESS.code, "Delete success.");
    }

    @Override
    public  Result<User> getUserByUserNameAndPassword(
            HttpServletRequest req, String userName, String password) {

        User user = userDao.getUserByUserNameAndPassword(userName, password);
        if (user == null) {
            return new Result<>(
                    Result.ResultStatus.FAILED.code, "User name or password are error.");
        } else {
            //将登陆用户信息添加到 session 中
            req.getSession().setAttribute("user", user);
            return new Result<>(
                    Result.ResultStatus.SUCCESS.code, "Login success.");
        }
    }

    @Override
    public void loginout(HttpServletRequest req) {
        req.getSession().removeAttribute("user");
    }
}
